#!/bin/bash

echo "=== Raft 业务应用演示 ==="

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "错误: 未找到Java环境，请先安装Java 11或更高版本"
    exit 1
fi

# 创建编译输出目录
mkdir -p target/classes

# 编译代码
echo "编译代码..."
javac -d target/classes -cp src src/main/java/demo/**/*.java src/main/java/business/**/*.java
if [ $? -ne 0 ]; then
    echo "编译失败，请检查代码"
    exit 1
fi
echo "编译完成"

# 清理函数
cleanup() {
    echo "正在关闭所有节点..."
    pkill -P $$
    exit 0
}

# 注册清理函数
trap cleanup INT TERM

# 定义集群配置
CLUSTER_CONFIG="node1:8081,node2:8082,node3:8083"

echo ""
echo "=== 可用的业务演示 ==="
echo "1. 启动单节点服务器 (端口8081)"
echo "2. 启动完整集群 (3节点: 8081-8083)"
echo "3. 启动KV客户端"
echo ""
echo "选择要运行的演示 (1-3):"
read choice

case $choice in
    1)
        echo "启动单节点服务器 (端口8081)..."
        java -cp target/classes business.server.RaftKVServer node1 8081 "$CLUSTER_CONFIG"
        ;;
    2)
        echo "启动3节点集群..."
        # 启动三个节点
        java -cp target/classes business.server.RaftKVServer node1 8081 "$CLUSTER_CONFIG" &
        echo "节点1已启动 (node1:8081)"
        sleep 2

        java -cp target/classes business.server.RaftKVServer node2 8082 "$CLUSTER_CONFIG" &
        echo "节点2已启动 (node2:8082)"
        sleep 2

        java -cp target/classes business.server.RaftKVServer node3 8083 "$CLUSTER_CONFIG" &
        echo "节点3已启动 (node3:8083)"

        echo ""
        echo "集群已启动完成！集群配置: $CLUSTER_CONFIG"
        echo "- 节点1 (node1): localhost:8081"
        echo "- 节点2 (node2): localhost:8082"
        echo "- 节点3 (node3): localhost:8083"
        echo ""
        echo "按 Ctrl+C 停止所有节点..."

        # 等待任意子进程结束
        wait
        ;;
    3)
        echo "启动KV客户端..."
        java -cp target/classes business.client.SimpleKVClient "$CLUSTER_CONFIG"
        ;;
    *)
        echo "退出演示"
        exit 0
        ;;
esac